package pmd5

import (
	"crypto/md5"
	"fmt"
	"io"
	"os"

	"gitee.com/daledi/public/encoding/pbase64"
)

func Encrypt(vals ...interface{}) []byte {
	if len(vals) == 0 {
		return nil
	}
	m := md5.New()
	for i := range vals {
		switch v := vals[i].(type) {
		case string:
			m.Write([]byte(v))
		case []byte:
			m.Write(v)
		}
	}
	return m.Sum(nil)[:md5.Size]
}

func EncryptString(vals ...interface{}) string {
	return fmt.Sprintf("%02x", Encrypt(vals...))
}

func EncryptB64(vals ...interface{}) string {
	return pbase64.Encode(Encrypt(vals...))
}

// FileMd5 获取文件的md5值。
func EncryptFile(fileName string) ([]byte, error) {
	file, err := os.Open(fileName)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	h := md5.New()
	if _, err := io.Copy(h, file); err != nil {
		return nil, err
	}
	return h.Sum(nil)[:md5.Size], nil
}
